package com.test.DDT.util;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCUtil {
    private static Connection conn;

    public static Object querySingleData(String sql) {
        conn = getConnection();
        QueryRunner queryRunner = new QueryRunner();

        Object ret = null;
        try {
            ret = queryRunner.query(conn, sql, new ScalarHandler<>());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return ret;
    }

    public static Object queryMapData(String sql) {
        conn = getConnection();
        QueryRunner queryRunner = new QueryRunner();
        Object ret = null;
        try {
            ret = queryRunner.query(conn, sql, new MapHandler());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return ret;
    }

    public static Object queryListData(String sql) {
        conn = getConnection();
        QueryRunner queryRunner = new QueryRunner();
        Object data = null;
        try {
            data = queryRunner.query(conn, sql, new MapListHandler());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return data;
    }


    public static Connection getConnection() {
        String url = "jdbc:mysql://shop.xxx.com/yami_shops?useUnicode=true&characterEncoding=utf-8";
        String user = "";
        String password = "";
        try {
            conn = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }
}
